import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, convertFromHTML, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const confirm = Modal.confirm;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { roleDistribution, roleDelete, roleAdd, roleUpdate } from '../../services/api';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './log.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = {
  ALL: '全部',
  ACTIVE: '生效',
  INACTIVE: '失效',
};

const statusArr = [
  {
    id: 'ACTIVE',
    name: '全部',
  },
];

const PAGE_SIZE = 20;

@connect(({ log, loading }) => {
  return {
    log,
    loading: loading.models.log,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    name: null,
  };

  componentDidMount() {
    this.init();
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'log/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
        name: '',
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'log/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'log/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        operator: fieldsValue.operator,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'log/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      name: null,
      code: null,
      type: null,
      status: 1,
      description: null,
    });
  };

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={16} sm={24}>
            <FormItem label="操作用户">
              {getFieldDecorator('operator')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleEdit(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    let { log: { data }, loading } = this.props;
    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (val, item, index) => (
          <span>{(data.pagination.current - 1) * data.pagination.pageSize + index + 1}</span>
        ),
      },
      {
        title: '操作用户',
        dataIndex: 'operator',
      },
      {
        title: '日志名称',
        dataIndex: 'name',
      },
      {
        title: '执行类型',
        dataIndex: 'type',
      },
      {
        title: '访问IP地址',
        dataIndex: 'ip',
      },
      {
        title: '访问时间',
        dataIndex: 'createTime',
        render: (val, item) => <span>{val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '-'}</span>,
      },
    ];

    return (
      <PageHeaderLayout title="日志列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
